package tk.xboot.boot.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Lazy(false)
@Component
public class R implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext ac;

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }
    public static <T> T getBean(Class<T> clazz) {
        return ac.getBean(clazz);
    }

    public static ReloadableResourceBundleMessageSource getMessageSource(){
        return ac.getBean(ReloadableResourceBundleMessageSource.class);
    }

    public static String getMessage(String code){
        Locale locale = LocaleContextHolder.getLocale();
        ReloadableResourceBundleMessageSource ms = ac.getBean(ReloadableResourceBundleMessageSource.class);
        return ac.getMessage(code, null, locale);
        /*String message = ac.getBean(MessageSource.class)
                .getMessage(code,null, locale);
        return message;*/
    }


    @Override
    public void destroy() throws Exception {
        ac = null;
    }
}
